package com.jumlabs.presentation.backend.web.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jumlabs.entities.navigation.NavigationItem;

public class RequestUINavigationInterceptor  extends HandlerInterceptorAdapter implements ApplicationContextAware  {
	  private ApplicationContext applicationContext;
	  /**
	   * In this case intercept the request BEFORE it reaches the controller
	   */
	  @Override
	  public boolean preHandle(HttpServletRequest request,
	      HttpServletResponse response, Object handler) throws Exception {
	    try {
	      // Do some changes to the incoming request object
	      updateRequest(request);
	      return true;
	    } catch (SystemException e) {	    
	      return false;
	    }
	  }

	  /**
	   * The data added to the request would most likely come from a database
	   */
	  private void updateRequest(HttpServletRequest request) {
		  NavigationItem topNavigation=(NavigationItem)applicationContext.getBean("topNavigation");
		   String requestURI=request.getRequestURI();
		   request.setAttribute("contextPath",request.getContextPath());
		  for(NavigationItem navItem:topNavigation.getNavigationItems()){
			 if(requestURI.contains(navItem.getLink().getHref())){
				 navItem.setSelected(true);
			 }
		  }
		  request.setAttribute("topNavigation", topNavigation);
	  }

	  /** This could be any exception */
	  private class SystemException extends RuntimeException {

	    private static final long serialVersionUID = 1L;
	    // Blank
	  }

	@Override
	public void setApplicationContext(ApplicationContext appcontext)
			throws BeansException {
		this.applicationContext=appcontext;
		
	}
	}